package com.mairuide.version_up.controller;

import com.mairuide._frame.base.BaseController;
import com.mairuide.bill.utils.ZipUtils;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.version_up.pojo.Company;
import com.mairuide.version_up.service.CompanyService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-03-08 10:38
 */
@Controller
@RequestMapping("version")
public class CompanyController extends BaseController{

    @Autowired
    CompanyService companyService;
    @Autowired
    private HttpSession session;
    /**
     * 打开版本升级的弹框
     */
    @RequestMapping(value = "/openVersionDialog", method = RequestMethod.GET)
    public Object openVersionDialog(ModelMap model){
        return "/versionDialog";
    }

    @RequestMapping("/getcurrent_version")
    @ResponseBody
    public Result getCurrentVersion(){
        Map currentVersion = companyService.getCurrentVersion();
        return new Result(true, StatusCode.OK,"查询成功", currentVersion);
    }
    //检测是否有新版本
    @RequestMapping("/isExist")
    @ResponseBody
    public Result isExist(){
        boolean haveUp = companyService.isHaveUp();
        if (haveUp){
            session.setAttribute("updateVersion","up");//升级
        }else{
            session.setAttribute("updateVersion","no-up");//不升级
        }
        return new Result(true, StatusCode.OK,"查询成功",haveUp);
    }
    @RequestMapping("/isOnLine")
    @ResponseBody
    public Result isOnLine(){
        Map onLine = companyService.isOnLine();
        if (onLine!=null){
            return new Result(true, StatusCode.OK,"查询成功");
        }else{
            return new Result(false, StatusCode.ERROR,"查询失败");
        }
    }

    /**
     * @Author 刘中华
     * @Date 2019/3/8 15:13
     * @Param []
     * @return com.mairuide.entity.Result
     * @Description 更新sql
     **/
    @RequestMapping("/upSql")
    @ResponseBody
    public Result getRemoteExe(){
        boolean portUsing = isPortUsing(5555);
        if (!portUsing){//说明没有开启本地socket服务
            HashMap<String, Object> map = new HashMap<>();
            map.put("flag",false);
            return new Result(false, StatusCode.ERROR,"查询失败",map);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Company one = companyService.getOne();
        Date update_time = one.getUpdate_time();
        String format = "";
        if (update_time==null){
            format = "2018-12-12 00:00:00";
        }else{
            format = sdf.format(update_time);
        }
        //第一步，更新sql
        companyService.upSql(format);
        //第二步 得到exe的最新下载地址
        session.removeAttribute("updateVersion");
        //Map remoteExe = companyService.getRemoteExe(format);
        //第三步 将本地的数据库表中的版本号更新到最新的
        companyService.updateCompanyInfo(one);
        //得到远程的服务器版本
        Map version = companyService.getVersion();
        Map<String,Object> data = (Map<String,Object>)version.get("data");
        //说明是可替换的
        if ("1".equals(String.valueOf(data.get("is_replace")))){
            //调用客户端client程序
            try{
                Socket s= new Socket("47.105.197.249", 6666);
                String property = new File("").getAbsolutePath();
                String tempUpdateDir=property+"\\tempUpdateDir";
                //删除文件夹
                FileUtils.deleteDirectory(new File(tempUpdateDir));
                System.out.println("更新文件临时目录》》"+ tempUpdateDir);
                if (!new File(tempUpdateDir).exists()){
                    new File(tempUpdateDir).mkdirs();
                }
                String fileName = tempUpdateDir+"\\"+"update.zip";
                File targetFile = new File(fileName);
                FileOutputStream outputStream = new FileOutputStream(targetFile);
                InputStream is = s.getInputStream();
                IOUtils.copy(is, outputStream);
                is.close();
                outputStream.close();
                System.gc();
                System.out.println("zip已下载到本地");
                s.close();
                //第二步，解压
                ZipUtils.unZip(targetFile,tempUpdateDir);
                System.out.println("zip解压完成");
                //第三步，调用更新程序
                Socket client= new Socket("127.0.0.1", 5555);
                //构建IO
                OutputStream os = client.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                //向服务器端发送一条消息
                bw.write("update");
                bw.flush();
                bw.close();
                os.close();
                client.close();
                System.out.println("向socket发送更新信息完成---------》》》》");
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("flag",true);
        return new Result(true, StatusCode.OK,"查询成功",map);
    }
    //检测本地的socket服务是否开启，如果没有开启就不执行升级的方法。
    public boolean isPortUsing(int port) {
        boolean flag = false;
        Socket socket=null;
        try {
            InetAddress theAddress = InetAddress.getByName("127.0.0.1");
            try {
                socket = new Socket(theAddress,port);
                flag = true;
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("本地socket没有开启");
            }finally {
                if(socket!=null){
                    socket.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }



}
